// pages/Comprehensive-query/Comprehensive-query.js
import { getAllSubProjectList, fetchSubProjectEmployees } from '../../api/project';
import { getSearchResult } from '../../api/attendance';

Page({
  data: {
    projects: [],
    names: [],
    employeesMap: {},
    selectedProject: {},
    selectedName: '',
    selectedDate: '',
    employees: []
  },

  onLoad() {
    this.loadProjects();
  },

  loadProjects() {
    getAllSubProjectList({}).then(response => {
      if (response.code === 1) {
        this.setData({ projects: response.data });
      } else {
        console.error('Failed to fetch projects');
      }
    }).catch(error => {
      console.error('Error fetching projects:', error);
    });
  },

  onProjectChange(e) {
    const selectedProject = this.data.projects[e.detail.value];
    this.setData({
      selectedProject
    }, () => {
      this.loadEmployeesByProject(selectedProject.id);
    });
  },

  onNameChange(e) {
    this.setData({
      selectedName: this.data.names[e.detail.value]
    });
  },

  onDateChange(e) {
    this.setData({
      selectedDate: e.detail.value
    });
  },

  loadEmployeesByProject(projectId) {
    fetchSubProjectEmployees(projectId).then(response => {
      if (response.code === 1) {
        const employeesMap = {};
        const names = response.data.map(employee => {
          employeesMap[employee.name] = employee.employeeId;
          return employee.name;
        });
        this.setData({ names, employeesMap });
      } else {
        console.error('Failed to fetch employees by project');
      }
    }).catch(error => {
      console.error('Error fetching employees by project:', error);
    });
  },

  onReset() {
    this.setData({
      selectedProject: {},
      selectedName: '',
      selectedDate: '',
      employees: []
    });
  },

  onQuery() {
    const { selectedProject, selectedName, selectedDate, employeesMap } = this.data;

    const projectId = selectedProject.id || 0;
    const employeeId = selectedName ? employeesMap[selectedName] : 0;
    const time = selectedDate || '';

    getSearchResult({ projectId, employeeId, time }).then(response => {
      if (response.code === 1) {
        const employees = response.data.map(employee => {
          const formattedTime = employee.formattedTime.split('-').slice(1).join('-');
          return { ...employee, formattedTime };
        });
        this.setData({ employees });
      } else {
        console.error('Failed to fetch search results');
      }
    }).catch(error => {
      console.error('Error fetching search results:', error);
    });
  }
});
